package com.anc.platform.config;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: dutao
 * @date: 2021/7/26 下午3:12
 * @description: 合链接口调用验签操作
 */
@Slf4j
@Component
public class SignAuthInterceptor implements HandlerInterceptor {





    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String path = request.getRequestURI();
        response.setContentType("application/json;charset=UTF-8");
        RequestWrapper requestWrapper;
        try {
            //由于reader只能读取一次，封装RequestWrapper 处理
//            if (request instanceof RequestWrapper) {
//                requestWrapper = (RequestWrapper) request;
//            } else {
//                requestWrapper = new RequestWrapper(request);
//            }
//            String requestBody = requestWrapper.getBody();
//            if (StringUtils.isBlank(requestBody)) {
//                return false;
//            }
            ServletInputStream inputStream = request.getInputStream();
            return true;
//            response.setStatus(401);
//            returnJson(response, "{\"code\": 100001,\"msg\": \"验签失败\"}");
//            return false;
        } catch (Exception e) {
            log.error("path={};message={};e={}", path, e.getMessage(), e);
            return false;
        }
    }


    /**
     * 返回客户端数据
     *
     * @param response
     * @param json
     * @throws Exception
     */
    private void returnJson(HttpServletResponse response, String json) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        try {
            writer = response.getWriter();
            writer.print(json);
        } catch (IOException e) {
            // ....
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
